<?php

namespace App\Http\Controllers;


use App\Services\PlivoService;
use App\Services\TwilioService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Plivo\XML\Response;
use App\Models\PhoneRecord;

class PlivoController extends CallBaseController
{
    protected $plivoService;
    protected $twilioSecret;

    public function __construct(PlivoService $plivoService,TwilioService $twilioService)
    {
        parent::__construct();
        $this->plivoService = $plivoService;
        $this->twilioSecret = $twilioService;

    }

    /**
     * XML
     */
    public function sendResponseWithPlivo(Request $request){
        $to = $request->input('to');
        $from = $request->input('from');
        $fs_user_id = $request->input('id');
        $user_id = $request->input('user_id');
        $task_id = $request->input('task_id','');
        $phone_setting_id = $request->input('phone_setting_id','');

        $response = new Response();
        $from = $request->input('from');
        $params = array(
            'callerId' => $from,
            'action' => env('APP_URL')."/api/plivo/record?id={$fs_user_id}&user_id={$user_id}&phone_setting_id={$phone_setting_id}&task_id={$task_id}",
            'method' => "GET",
            'redirect' => "true",
            'callbackUrl' => env('APP_URL')."/api/plivo/video",
            'callbackMethod' => 'POST'
        );

        $params1 = array(
            'action' => env('APP_URL')."/api/plivo/videoUrl?id={$fs_user_id}&user_id={$user_id}&phone_setting_id={$phone_setting_id}&task_id={$task_id}",
            'startOnDialAnswer' => "true",
            'redirect' => "false",
               'method' => "GET",
        );
        $response->addRecord($params1);


        $dial = $response->addDial($params);
        $number = $request->input('to');
        $dial->addNumber($number);
        Log::info('XML回调',['++++++++++++']);
        Header('Content-type: text/xml');
        echo($response->toXML());
    }

    /**
     *  挂断的URL
     */
    public function hangup(){
        $r = new Response();
        $params = array(
            'reason' => 'rejected', # Specify the reason for hangup
        );

        $r->addHangup($params);
        Header('Content-type: text/xml');
        echo($r->toXML());
    }

    /**
     * 1.返回录音文件地址
     * @param Request $request
     */
    public function videoUrl(Request $request){
        $data = $request->all();
        Log::info('Plivo录音文件地址记录1',[$data]);
        PhoneRecord::create([
            'call_sid'=> $data['CallUUID'],
            'fs_user_id' => $data['id'],
            'user_id' => $data['user_id'],
            'task_id' => isset($data['task_id'])?$data['task_id']:null,
            'phone_setting_id' => $data['phone_setting_id'],
            'recording_sid'=> isset($data['RecordingID'])?$data['RecordingID']:'',
            'recording_url' => $data['RecordUrl']
        ]);

        //通话状态为0的时候才去修改
        if(isset($data['task_id'])){
            $res = DB::table('fs_user_tasks')->where([
                ['task_id','=',$data['task_id']],
                ['fs_user_id','=',$data['id']],
            ])->first();
            if($res->status===0){
                DB::table('fs_user_tasks')->where([
                    ['task_id','=',$data['task_id']],
                    ['fs_user_id','=',$data['id']],
                ])->update(['status'=>1,'call_time'=>Carbon::now()]);
            }
        }

        //会员微信存在则通话次数+1，否则创建一个为1的空微信
        $res = DB::table('fs_user_has_ims')->where('fs_user_id',$data['id'])->count();
        if($res){
            DB::table('fs_user_has_ims')->where([
                ['fs_user_id','=',$data['id']],
            ])->increment('phone_num');
        }else{
            $res = DB::table('fs_user_has_ims')->insert([
                'fs_user_id' =>$data['id'],
                'phone_num' => 1,
            ]);
        }
        //统计
        if(isset($data['task_id'])){
            $arr = [
                'fs_user_id' => $data['id'],
                'task_id' => $data['task_id']
            ];
            $this->twilioSecret->taskStatus($arr);
        }
        //清空ANSWER URL
        $phone_res = DB::table('phones')->where([
            ['phone_setting_id','=',$data['phone_setting_id']],
            ['user_id','=',$data['user_id']]
        ])->first();
        if($phone_res){
            $this->plivoService->resetApp($phone_res->apps);
        }
    }

    /**
     *  2.通话记录
     */
    public function record(Request $request){
        $data = $request->all();
        //更新通话状态
        PhoneRecord::where('call_sid',$data['CallUUID'])->update([
            'call_status' => isset($data['DialStatus'])?$data['DialStatus']:''
        ]);

        Log::info('Plivo保持通话记录2',[$data]);
    }

    /**
     *  3录音记录
     */
    public function video(Request $request,PlivoService $plivoService){
        //更新开始通话时间，结束通话时间，通话时长
        $data = $request->all();
        if(isset($data['DialBLegDuration']) && $data['DialBLegDuration'] > 0){
            $record = PhoneRecord::where('call_sid',$data['CallUUID'])->first();
            $voice_url = $plivoService->voiceUpload($record->recording_url,$record->call_sid);
            if($voice_url){
                PhoneRecord::where('call_sid',$data['CallUUID'])->update([
                    'voice_url' => $voice_url,
                    'created_at'=>isset($data['StartTime'])?$data['StartTime']:null,
                    'updated_at'=> isset($data['EndTime'])?$data['EndTime']:null,
                    'recording_time' => isset($data['DialBLegDuration'])?$data['DialBLegDuration']:0
                ]);
            }
        }else{
            PhoneRecord::where('call_sid',$data['CallUUID'])->update([
                'created_at'=>isset($data['StartTime'])?$data['StartTime']:null,
                'updated_at'=> isset($data['EndTime'])?$data['EndTime']:null,
                'recording_time' => isset($data['DialBLegDuration'])?$data['DialBLegDuration']:0
            ]);
        }
        Log::info('Plivo通话结束时记录3',[$data]);
    }
}
